<template>
  <section class="todoapp">
    <TodoHeader @add="handleAdd"></TodoHeader>

    <TodoMain
      :list="list2"
      @del="handleDel"
      @state="handlestate"
      @changeAll="handleAll"
    ></TodoMain>

    <TodoFooter
      :flag="flag"
      :list="list"
      @delCompleted="clearCompleted"
      @changeFlag="
        (val) => {
          flag = val;
        }
      "
    ></TodoFooter>
  </section>
</template>

<script>
import TodoFooter from "./components/TodoFooter.vue";
import TodoHeader from "./components/TodoHeader.vue";
import TodoMain from "./components/TodoMain.vue";

export default {
  components: { TodoHeader, TodoMain, TodoFooter },
  data() {
    return {
      list: [
        { id: 12, name: "吃饭", isDone: false },
        { id: 14, name: "听歌", isDone: true },
        { id: 23, name: "洗澡", isDone: true },
        { id: 34, name: "睡觉", isDone: false },
        { id: 35, name: "游戏", isDone: false },
      ],
      list: JSON.parse(localStorage.getItem("todo")) || [],
      flag: 1, //1.显示全部任务 2.显示进行中 3. 显示已完成的
    };
  },
  // 定义删除方法
  methods: {
    handleDel(id) {
      // console.log(id);
      //filter数据筛选
      this.list = this.list.filter((item) => {
        item.isDone === false;
      });
    },
    handleAdd(todoname) {
      this.list.unshift({
        id: Date.now,
        name: todoname,
        isDone: false,
      });
    },
    handlestate(id) {
      // this.list.forEach(item=>{
      //   if(item.id === id){
      //     item.isDone = !item.isDone
      //   }
      // })
      // console.log(id);
      let res = this.list.find((item) => item.id === id);
      // 取反
      res.isDone = !res.isDone;
    },
    clearCompleted() {
      //清除已完成,保留未完成isDone=false的
      this.list = this.list.filter((item) => {
        item.isDone === false;
      });
    },
    handelAll(val) {
      this.list.forEach((item) => {
        item.isDone = val;
      });
    },
  },
  computed: {
    list2() {
      if (this.flag === 1) {
        return this.list;
      } else if (this.flag === 2) {
        return this.list.filter((item) => item.isDone === false);
      } else if (this.flag === 3) {
        return this.list.filter((item) => item.isDone === true);
      }
    },
  },
  watch: {
    list: {
      handler(val) {
        //val   表示变化后的 list
        localStorage.setItem("todo", JSON.stringify(val));
      },
      deep:true,
      // immediate:true
    },
  },
};
</script>

<style>
</style>
